package com.baseproject.volley;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by hp on 2017/3/28.
 */

public class JSONHttpService implements IHttpService {
    private IHttpListener httpListener;
    private HttpClient httpClient = new DefaultHttpClient();
    private String url;

    //请求参数 字节数组
    private byte[] requestData;
    private HttpRequestBase httpRequestBase;

    @Override
    public void setUrl(String url) {
        this.url = url;
    }

    /**
     * 子线程
     */
    @Override
    public void execute() {
        httpRequestBase = new HttpPost(url);
        if (null != requestData) {
            //设置请求参数
            ByteArrayEntity byteArrayEntity = new ByteArrayEntity(requestData);
            ((HttpPost) httpRequestBase).setEntity(byteArrayEntity);
        }
        try {
            httpClient.execute(httpRequestBase, new HttpResponseHander());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private class HttpResponseHander extends BasicResponseHandler {
        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException {

            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                HttpEntity httpEntity = response.getEntity();
                if (null != httpListener) {
                    try {
                        InputStream inputStream = httpEntity.getContent();
                        httpListener.onSuccess(inputStream);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                if (null != httpListener) {
                    httpListener.onError();
                }
            }
            return null;
        }
    }

    @Override
    public void setHttpCallBack(IHttpListener httpListener) {
        this.httpListener = httpListener;
    }

    @Override
    public void setRequestData(byte[] requestData) {
        this.requestData = requestData;
    }
}
